<?php
class Shopcart_model extends CI_Model 
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper('cookie');
		$this->load->model('Goods_model','goods');
	}
	
	public function add($goodsId,$num = 1)
	{		
		
		$shopcart = get_cookie('Shop_Cart');	
		if($shopcart)
		{
			$shopcart = unserialize($shopcart);
		}
		else
		{		
			$shopcart = array(	);
		}
		
		if(isset($shopcart[$goodsId]))
		{
			$shopcart[$goodsId]['sum'] += $num;	
		}
		else
		{		
			$shopcart[$goodsId] = array(
				'sum' => $num,
				'price' => $this->goods->get_goods_price_by_id($goodsId),		
			);
		}		
		set_cookie('Shop_Cart',serialize($shopcart),86500);
		return $shopcart;
	}
	
	public function setSum($goodsId,$num)
	{
		$shopcart = get_cookie('Shop_Cart');
		if($shopcart)
		{
			$shopcart = unserialize($shopcart);
			if(isset($shopcart[$goodsId])){
				$shopcart[$goodsId]['sum'] = $num;
				set_cookie('Shop_Cart',serialize($shopcart),86500);
			}
		}		
	}
	
	public function delete()
	{
		delete_cookie('Shop_Cart');
	}
	
	public function getAll()
	{
		$shopcart = get_cookie('Shop_Cart');
		if($shopcart)
		{
			$shopcart = unserialize($shopcart);
			$return = array();
			foreach ($shopcart as $gid=>$v)
			{
				$goods = $this->goods->get_goods_by_id($gid);
				if(!$goods)
					continue;
				$goods['sum'] = $v['sum'];
				$goods['price'] = $v['sum']*$goods['shop_price'];
				$return[] = $goods;
			}
			return $return;
		}
		return false;
	}

	public function remove($id)
	{
		return true;
	}
}